<template>
  <div class="app-container">
    <!-- 搜索筛选区域 -->
    <div class="search-container">
      <el-input
        v-model="queryParams.searchParam"
        placeholder="请输入昵称、用户名或者手机号"
        clearable
        style="width: 300px; margin-right: 10px;"
        @keyup.enter.native="handleQuery"
      />
      <el-select v-model="queryParams.roleId" placeholder="全部" clearable style="width: 120px; margin-right: 10px;">
        <el-option label="全部" value="" />
        <el-option label="游客" value="100" />
        <el-option label="企业用户" value="101" />
        <el-option label="联企用户" value="102" />
        <el-option label="领导" value="103" />
      </el-select>
      <el-button type="primary" @click="handleQuery">查询</el-button>
    </div>

    <!-- 用户列表表格 -->
    <el-table v-loading="loading" :data="userList" stripe style="width: 100%">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="用户" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <el-avatar :size="32" :src="scope.row.headImageUrl" icon="el-icon-user-solid"></el-avatar>
            <span style="margin-left: 8px;">{{ scope.row.id }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="OPENID" prop="openId"/>
      <el-table-column label="用户昵称" prop="nickName" align="center">
        <template slot-scope="scope">
          {{ scope.row.nickName || '未设置' }}
        </template>
      </el-table-column>

      <el-table-column label="角色类型" align="center">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
          <!-- <el-tag :type="getRoleTypeStyle(scope.row.roleType)" size="small">
            {{ getRoleTypeText(scope.row.roleType) }}
          </el-tag> -->
        </template>
      </el-table-column>

      <el-table-column label="手机号码" prop="phone"  align="center">
        <template slot-scope="scope">
          {{ scope.row.phone || '-' }}
        </template>
      </el-table-column>

      <el-table-column label="用户状态"  align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'" size="small">
            {{ scope.row.status === 0 ? '正常' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作"  align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.roleName === '企业用户'"
            type="primary"
            size="mini"
            @click="handleSwitchRole(scope.row)"
          >替换此企业人员</el-button>
          <el-button
            v-if="scope.row.roleName === '联企用户'"
            type="danger"
            size="mini"
            @click="handleSwitchRole(scope.row)"
          >替换此联企人员</el-button>
          <span
            v-if="scope.row.roleName === '游客'"
            class="action-link"
            @click="handleSwitchRole(scope.row)"
          >设为联企人员</span>
          <span
            v-if="scope.row.roleName === '游客'"
            class="action-link"
            @click="setToLeader(scope.row)"
          >设置为领导</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（通用组件） -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 部门选择弹框 -->
    <el-dialog
      title="选择部门"
      :visible.sync="branchDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-loading="branchLoading">
        <el-tree
          :data="branchList"
          :props="branchTreeProps"
          node-key="deptId"
          :default-expand-all="true"
          :highlight-current="true"
          @node-click="handleBranchSelect"
        >
          <span slot-scope="{ node, data }" class="custom-tree-node">
            <span>{{ data.deptName }}</span>
          </span>
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="branchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirmBranch" :disabled="!selectedBranch">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 替换账号弹框 -->
    <el-dialog
      :title="replaceDialogTitle"
      :visible.sync="replaceDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <div>
        <div style="margin-bottom: 15px;">
          <span>新账号</span>
        </div>
        <el-input
          v-model="replaceAccount"
          placeholder="请输入新账号绑定的手机号"
          clearable
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="replaceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirmReplace" :disabled="!replaceAccount">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMember, listBranch, setMembBranch,replaceToOther } from "@/api/biz/api";
import role from "@/views/system/role/index.vue";

export default {
  name: "MpUser",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 用户列表数据
      userList: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 50,
        searchParam: null,
        roleId: null
      },
      // 部门选择弹框相关
      branchDialogVisible: false,
      branchLoading: false,
      branchList: [],
      selectedBranch: null,
      currentUser: null,
      branchTreeProps: {
        children: 'children',
        label: 'name'
      },
      replaceParam:{
        roleName:'',
        targetAccount:'',
        memberId:0,
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 获取角色类型文本 */
    getRoleTypeText(roleType) {
      const typeMap = {
        'enterprise': '企业用户',
        'associated': '联企用户'
      };
      return typeMap[roleType] || '未知';
    },
    /** 获取角色类型样式 */
    getRoleTypeStyle(roleType) {
      const styleMap = {
        'enterprise': 'primary',   // 企业用户 - 蓝色
        'associated': 'danger'     // 联企用户 - 红色
      };
      return styleMap[roleType] || '';
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      // 实际API调用示例
      console.log('请求参数：', this.queryParams);
      listMember(this.queryParams).then(response => {
        this.userList = response.data?.records || [];
        this.total = response.data?.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取用户列表失败:', error);
        this.userList = [];
        this.total = 0;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 切换角色 */
    handleSwitchRole(row) {
      let _self = this;
      let currentRoleName = row.roleName;
      // 如果是游客，显示部门选择弹框
      if (currentRoleName === '游客') {
        this.currentUser = row;
        this.selectedBranch = null;
        this.branchDialogVisible = true;
        this.getBranchList();
        return;
      }
      
      // 如果是企业用户或联企用户，显示替换账号弹框
      if (newRoleType === '企业用户' || newRoleType === '联企用户') {
        this.currentUser = row;
        this.replaceAccount = '';
        this.replaceUserType = newRoleType;
        this.replaceDialogTitle = `改变【${newRoleType}】的登录微信`;
        this.replaceDialogVisible = true;
        return;
      }
      
      const actionText = newRoleType === '企业用户' ? '企业用户' : newRoleType === '联企用户' ? '联企用户' : '游客';
      this.$modal.confirm(`确认将用户 ${row.nickname || row.userId} 切换到${actionText}？`).then(() => {
        // 实际应该调用API
        // switchUserRole(row.userId, newRoleType).then(() => {
        //   this.$modal.msgSuccess("切换成功");
        //   this.getList();
        // });
        
        // 模拟切换成功
        _self.replaceParam.roleName = currentRoleName;
        _self.replaceParam.memberId = row.id;
        _self.replaceParam.targetAccount = inputVal.value;
        replaceToOther(_self.replaceParam).then(response=>{
          _self.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(error=>{
          this.$modal.msgError(response.msg)
        })
      }).catch(() => {
        this.$modal.msgInfo("操作已取消");
      });
    },
    setToLeader(row){
      this.$modal.confirm(`确认将此游客设置为领导`).then(() => {
        //TODO
      }).catch(() => {
        this.$modal.msgInfo("操作已取消");
      });
    },
    /** 获取部门列表 */
    getBranchList() {
      this.branchLoading = true;
      listBranch().then(response => {
        this.branchList = response.data || [];
        this.branchLoading = false;
      }).catch(error => {
        console.error('获取部门列表失败:', error);
        this.$modal.msgError("获取部门列表失败");
        this.branchLoading = false;
      });
    },
    /** 选择部门 */
    handleBranchSelect(data) {
      console.log('data is ',data);
      this.selectedBranch = data;
    },
    /** 确认选择部门 **/
    handleConfirmBranch() {
      if (!this.selectedBranch) {
        this.$modal.msgWarning("请选择一个部门");
        return;
      }
      console.log('this.currentUser === ',this.currentUser)
      const data = {
        memberId: this.currentUser.id,
        branchId: this.selectedBranch.deptId
      };

      setMembBranch(data).then(response => {
        this.$modal.msgSuccess("设置联企人员成功");
        this.branchDialogVisible = false;
        this.getList(); // 刷新列表
      }).catch(error => {
        console.error('设置联企人员失败:', error);
        // this.$modal.msgError("设置联企人员失败");
      });
    },
    /** 确认替换账号 */
    handleConfirmReplace() {
      if (!this.replaceAccount) {
        this.$modal.msgWarning("请输入要替换的账号");
        return;
      }
      
      const data = {
        memberRole:this.replaceUserType,
        memberId: this.currentUser.id,
        targetAccount: this.replaceAccount, 
      };
      
      replaceToOther(data).then(response => {
        this.$modal.msgSuccess("替换账号成功");
        this.replaceDialogVisible = false;
        this.getList(); // 刷新列表
      }).catch(error => {
        console.error('替换账号失败:', error);
        // this.$modal.msgError("替换账号失败");
      });
    }
  },
};
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 4px;
}

.action-link {
  color: #409EFF;
  cursor: pointer;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-link:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
  text-decoration: underline;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

</style>
